package com.qfedu.fmmall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.service.OrdersService;
import com.qfedu.fmmall.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private OrdersService ordersService;
 /**
  *
  * 支付回调
  */
 @RequestMapping("/callback")
 public Map<String, String> success(HttpServletRequest request){
  ServletInputStream inputStream=null;
  StringBuilder s=new StringBuilder();
     System.out.println(1);
  try {
    inputStream = request.getInputStream();
    byte[] bytes = new byte[1024];
    int len = -1;
    while ((len=inputStream.read(bytes)) != -1){
           s.append(new String(bytes,0,len));
    }
      Map<String, String> stringStringMap = WXPayUtil.xmlToMap(s.toString());
       if (stringStringMap!=null&&"success".equalsIgnoreCase(stringStringMap.get("return_code"))){
//            1.支付成功！
//           2.修改订单状态
           Orders orders = ordersService.getOne(new LambdaQueryWrapper<Orders>().eq(Orders::getOrderId, stringStringMap.get("out_trade_no")));
           orders.setStatus("2");
           boolean updateById = ordersService.updateById(orders);
//           响应websocket连接
          WebSocketServer.sendMsg(stringStringMap.get("out_trade_no"), "1");

           if (updateById) {
               //            3.响应微信支付平台
               HashMap<String, String> map = new HashMap<>();
               map.put("return_code","success");
               map.put("return_msg","OK");
               map.put("appid",stringStringMap.get("appid"));
               map.put("result_code","success");

               return WXPayUtil.xmlToMap(map.toString());
           }else {
               return null;
           }
       }else {
            //支付失败
          return null;
       }
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

}
